package com.hs.chd.action.data;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hs.chd.service.IDataService;
import com.hs.core.action.BaseAction;
import com.hs.core.cache.DictCacheUtil;
import com.hs.core.db.DBMgr;
@Controller   
public class CatagoryController  extends BaseAction {
    private static final Logger logger = Logger.getLogger(CatagoryController.class);
	private IDataService dataService;
	@Autowired  
	public void setDataService(IDataService dataService) {
		this.dataService = dataService;
	}
	/**
	  * 方剂分类数据维护
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/catagory/pretag.do", method = RequestMethod.GET)   
   public ModelAndView pretag(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 DBMgr dbo = this.getDbo(request);
         Map treedata = getTreeStr(dbo,"1");
         modelMap.addAllAttributes(treedata);
		 return new ModelAndView("app/catagory/pretag",modelMap);
		 
	 } 
	 /**
	  * 证候分类数据维护
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/catagory/symtag.do", method = RequestMethod.GET)   
	 public ModelAndView symtag(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 DBMgr dbo = this.getDbo(request);
         Map treedata = getTreeStr(dbo,"2");
         modelMap.addAllAttributes(treedata);
		 return new ModelAndView("app/catagory/symtag",modelMap);
		 
	 } 
	 /**
	  * 中药分类数据维护
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/catagory/herbtag.do", method = RequestMethod.GET)   
	 public ModelAndView herbtag(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 DBMgr dbo = this.getDbo(request);
         Map treedata = getTreeStr(dbo,"3");
         modelMap.addAllAttributes(treedata);
		 return new ModelAndView("app/catagory/herbtag",modelMap);
		 
	 } 
	 /**
	  * 病名分类数据维护
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/catagory/distag.do", method = RequestMethod.GET)   
	 public ModelAndView distag(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
//		 DBMgr dbo = this.getDbo(request);
//         Map treedata = getTreeStr(dbo,"4");
//         modelMap.addAllAttributes(treedata);
		 return new ModelAndView("app/catagory/discata",modelMap);
		 
	 } 
	 
	 /**
	  * 主题分类数据维护
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/catagory/tagsframe.do", method = RequestMethod.GET)   
   public ModelAndView tagsframe(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 
		 return new ModelAndView("app/catagory/tagsframe",modelMap);
		 
	 }  
	 /***
	  * 生成左侧分类树
	  * @param dbo
	  * @return
	  */
	 private Map getTreeStr(DBMgr dbo,String type){
		 Map hashMap = new HashMap();
		 StringBuffer tree1 = new StringBuffer("[");
		 StringBuffer tree2 = new StringBuffer("[");
		 StringBuffer tree3 = new StringBuffer("[");
		 StringBuffer tree4 = new StringBuffer("[");
		 String sql = "select * from SCHD_TAGS where isdelete =1 and tagtype=" + type +
		 		" order by isroot";
		 List nodelist = dbo.queryList(sql, null);
		 for(int i =0;i<nodelist.size();i++){
			 Map data = (Map)nodelist.get(i);
			 String id = data.get("ID") + "";
			 String pid = data.get("PID") + "";
			 String code = (String)data.get("TAGCODE");
			 String name = (String)data.get("TAGNAME");
			 String ttype  =  data.get("TAGTYPE")+"";
			 //方剂分类
			 if("1".equals(ttype)){
				 tree1.append("{id:").append(id).append(",pId:").append(pid).append(",");
				 tree1.append("name:\"").append(name).append("\",open:true},");
			 //中药分类
			 }else if("2".equals(ttype)){
				 tree2.append("{id:").append(id).append(",pId:").append(pid).append(",");
				 tree2.append("name:\"").append(name).append("\",open:true},");
			 //证候分类
			 }else if("3".equals(ttype)){
				 tree3.append("{id:").append(id).append(",pId:").append(pid).append(",");
				 tree3.append("name:\"").append(name).append("\",open:true},");
			 //病名分类			
			 }else if("4".equals(ttype)){
				 tree4.append("{id:").append(id).append(",pId:").append(pid).append(",");
				 tree4.append("name:\"").append(name).append("\",open:true},");
			 } 
		 }
		 hashMap.put("treeStr1",cutStr(tree1.toString())+"]" );
		 hashMap.put("treeStr2",cutStr(tree2.toString())+"]" );
		 hashMap.put("treeStr3",cutStr(tree3.toString())+"]" );
		 hashMap.put("treeStr4",cutStr(tree4.toString())+"]");
		 return hashMap;
	 }
	 private static String cutStr(String str){
		 if(str.lastIndexOf(',') != -1){
			 str = str.substring(0, str.length()-1);
		 }
		 return str;
	 }
	 /**
	  * 异步加载主题分类树
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/catagory/maintree.do")   
    public void maintree(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 long start = System.currentTimeMillis()/1000;
		 
		 StringBuilder builder = new StringBuilder();
		 Map datacache = new HashMap();
			builder.append("<?xml version='1.0' encoding='UTF-8'?>\n");
			builder.append("<tree id=\"0\">\n");
			DBMgr dbutil = this.getDbo(request); 
			builder.append("<item text=\"").append("病名分类").append("\" nocheckbox=\"1\" open=\"0\" id=\"").append("4").append("\">");
			builder.append("\n"); 
			List alldataList = dbutil.queryList("select a.*,to_char(a.id) as idstr from SCHD_TAGS a where   pid=4   order by a.ordernum", null);
			logger.debug("alldataList:" + alldataList);
			for(int i=0;i<alldataList.size();i++){
				
				Map tag  = (Map)alldataList.get(i);
				logger.debug("map:" + tag);
				String tagname = (String)tag.get("tagname");
				String tagid = (String)tag.get("idstr");
				String tagpid = (String)tag.get("pidstr");
				String tagtype =  tag.get("tagtype") + "";
				    builder.append("<item ");
//				    DictCacheUtil dictutil = DictCacheUtil.getInst();
//				    StringBuilder builderstr = new StringBuilder();
 					builder.append("  nocheckbox=\"1\" open=\"0\" child=\"1\" id=\"").append(tagid).append("\" ");
					builder.append(">\n"); 
					builder.append("<itemtext><![CDATA["); 
				    builder.append(tagname); 
					builder.append("]]></itemtext>").append("\n");
					builder.append("<userdata name=\"tagtype\">").append(tagtype).append("</userdata>\n"); 
					
					builder.append("</item>\n"); 
				
			}
			  
			builder.append("</item>\n"); 
			builder.append("</tree>"); 
			logger.debug("start:" + start);
			
			logger.info("builder：" + builder.toString());
			 
	    	try {
	    		 
				PrintWriter w = response.getWriter(); 
				 w.println(builder.toString());
				 w.flush();
				 w.close();
				 logger.debug("end:" + System.currentTimeMillis()/1000);
			} catch (IOException e) {
				 throw e;
			} 
			
		 
	 } 
	 /**
	  * 异步加载树节点
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/catagory/loadnode.do")   
    public void loadnode(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 long start = System.currentTimeMillis()/1000;
		 String pid = request.getParameter("id");
		 StringBuilder builder = new StringBuilder();
		 builder.append("<?xml version='1.0' encoding='UTF-8'?>\n");
		 builder.append("<tree id=\""+pid+"\">\n");
		 logger.debug("pid:"+pid);
		  DictCacheUtil dictutil = DictCacheUtil.getInst();
		 
		 Map datacache = new HashMap(); 
			DBMgr dbutil = this.getDbo(request);  
			List alldataList = dbutil.queryList("select a.*,to_char(a.id) as idstr,to_char((select count(*) from SCHD_TAGS where pid=a.id)) as ischild from SCHD_TAGS a where  isdelete =1 and pid=?   order by a.ordernum", new Object[]{pid});
			for(int i=0;i<alldataList.size();i++){
				Map tag  = (Map)alldataList.get(i);
				String tagname = (String)tag.get("tagname");
				String tagid = (String)tag.get("idstr"); 
				String ischild = (String)tag.get("ischild"); 
				String tagtype =  tag.get("tagtype") + ""; 
			    builder.append("<item "); 
				builder.append(" open=\"0\" nocheckbox=\"1\"");
				if("0".equals(ischild)){
					builder.append(" child=\"0\" ");
				}else{
					builder.append(" child=\"1\" ");
				}
				builder.append("id=\"").append(tagid).append("\" ");
				builder.append(">\n"); 
				builder.append("<itemtext><![CDATA["); 
				 //查询中英文对照
			    if(null != dictutil.getSubjectcodeBycnKey(tagname)){
			    	builder.append(tagname).append("(").append(dictutil.getSubjectcodeBycnKey(tagname)).append(")");
			    }else{
			    	builder.append(tagname); 
			    }
				builder.append("]]></itemtext>").append("\n");
				builder.append("<userdata name=\"tagtype\">").append(tagtype).append("</userdata>\n"); 
				builder.append("</item>\n"); 
				
			}
			builder.append("</tree>\n");  
			 
			logger.debug("start:" + start);
			
			logger.info("builder：" + builder.toString());
		 
	    	try {
	    		 
				PrintWriter w = response.getWriter(); 
				 w.println(builder.toString());
				 w.flush();
				 w.close();
				 logger.debug("end:" + System.currentTimeMillis()/1000);
			} catch (IOException e) {
				 throw e;
			} 
			
		 
	 } 
}
